package com.cslg.ac.demo.service.auth.idCard;

import com.alibaba.fastjson.JSONObject;
import com.cslg.ac.demo.constant.ResponseCode;
import com.cslg.ac.demo.dao.auth.idCard.IdCardDAO;
import com.cslg.ac.demo.dao.user.person.PersonInfoDAO;
import com.cslg.ac.demo.dao.user.po.team.TeamHeadPO;
import com.cslg.ac.demo.dao.user.team.TeamHeadDAO;
import com.cslg.ac.demo.dao.user.team.TeamInfoDAO;
import com.cslg.ac.demo.dao.user.UserAuthDAO;
import com.cslg.ac.demo.dao.user.po.person.PersonInfoPO;
import com.cslg.ac.demo.dao.user.po.team.TeamInfoPO;
import com.cslg.ac.demo.dao.user.po.UserAuthPO;
import com.cslg.ac.demo.entity.user.team.TeamHead;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

@Service
@PropertySource(value = {"classpath:auth.properties"},encoding="utf-8")
public class IdCardService {


    @Autowired
    UserAuthDAO userAuthDAO;
    @Autowired
    PersonInfoDAO personInfoDAO;
    @Autowired
    TeamInfoDAO teamInfoDAO;
    @Autowired
    TeamHeadDAO teamHeadDAO;

    @Value("${url}")
    String url;
    @Value("${appCode}")
    String appCode;
    @Value("${appKey}")
    String appKey;

    public int auth(String idCard,String name,int id){
        String param = "cardNo=" + idCard + "&realName=" + name;
        String result = IdCardDAO.APISTORE_POST(url,param,appCode);
        JSONObject jsonObject = JSONObject.parseObject(result);
        int errorCode = (int)jsonObject.get("error_code");
        if(errorCode != 0){
            return ResponseCode.AUTH_FAILED;
        }
        UserAuthPO userAuthPO = userAuthDAO.selectById(id);
        userAuthPO.setIdCardAuth(0);
        userAuthDAO.update(userAuthPO);
        PersonInfoPO personInfoPO = personInfoDAO.selectById(id);
        personInfoPO.setIdCard(idCard);
        personInfoPO.setRealName(name);
        personInfoDAO.updateAllById(personInfoPO);
        return ResponseCode.REQUEST_SUCCESSED;
    }

    /**
     * 是否验证了身份证号
     * @return
     */
    public String isAuth(int id){
        UserAuthPO userAuthPO = userAuthDAO.selectById(id);
        if(userAuthPO == null){
            return null;
        }
        if(userAuthPO.getIdCardAuth() == 1){
            return null;
        }else if(userAuthPO.getIdCardAuth() == 0){
            PersonInfoPO personInfoPO = personInfoDAO.selectById(id);
            if(personInfoPO != null){
                return personInfoPO.getRealName();
            }
            TeamHeadPO teamHeadPO = teamHeadDAO.selectById(id);
            return teamHeadPO.getRealName();
        }
        return null;
    }

}
